//
//  QRCodeViewController.m
//  DzNews
//
//  Created by zengyuan on 11/2/14.
//  Copyright (c) 2014 zengyuan. All rights reserved.
//

#import "QRCodeViewController.h"
//#import "UIViewController+DZTabbar.h"
#import "RegexKitLite.h"
//#import "WebToolViewController.h"
//#import "DzNewsUse.h"
//#import "NewsDetailViewController.h"
//#import "ActivityDetailViewController.h"
//#import "ShopDetailViewController.h"
#import "InputDeviceViewController.h"

@interface QRCodeViewController ()<UIImagePickerControllerDelegate>

@end


#define SCANREGION CGRectMake(30, 70, kScreenWidth - 60, kScreenHeight-70)

@implementation QRCodeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    
    [self prepare];

    self.titleLabel.text = @"扫描设备二维码";
    
//    scanRegion = CGRectMake(30, 70, kScreenWidth - 60, 300);
    
//    CGRectInset(self.view.bounds, 15, 50);
    
    
    float btn_width = 65;
    float btn_height= 80;

    float btn_interval = 30;

    
    from_libra_btn = [[YellowTitleBtn alloc] init];
    [from_libra_btn setFrame:CGRectMake((self.view.frame.size.width - btn_width*2 - btn_interval)/2, 40, btn_width, btn_height)];
    [from_libra_btn setImage:[UIImage imageNamed:@"qr_fromlib"] forState:UIControlStateNormal];
    [from_libra_btn setImage:[UIImage imageNamed:@"qr_fromlib_h"] forState:UIControlStateHighlighted];
    [from_libra_btn addTarget:self action:@selector(pickFromLib) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:from_libra_btn];
    [from_libra_btn addTitle:@"图片识别"];
    
    light_btn = [[YellowTitleBtn alloc] init];
    [light_btn setFrame:CGRectMake(from_libra_btn.frame.origin.x + from_libra_btn.frame.size.width + btn_interval, 40, btn_width, btn_height)];
    [light_btn setImage:[UIImage imageNamed:@"qr_light_off"] forState:UIControlStateNormal];
    [light_btn setImage:[UIImage imageNamed:@"qr_light_on"] forState:UIControlStateSelected];
    [light_btn addTarget:self action:@selector(turnLight) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:light_btn];
    [light_btn addTitle:@"开启灯光"];
    
    

}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES];
    
    [self startReading];
}

-(void)turnLight{
    
    light_btn.selected = !light_btn.selected;
    if (light_btn.selected) {
        self.readerView.torchMode = 1;
        
        [light_btn addTitle:@"关闭灯光"];

    }else{
        self.readerView.torchMode = 0;
        
        [light_btn addTitle:@"开启灯光"];

    }
}

-(void)pickFromLib{
    [self.readerView stop];
    
    UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
    mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    mediaUI.mediaTypes =  [UIImagePickerController         availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    mediaUI.allowsEditing = NO;
    mediaUI.delegate = self;
    [self presentViewController:mediaUI animated:YES completion:^{
        
    }];
}


-(void)prepare{
    //处理模拟器
    if (!TARGET_IPHONE_SIMULATOR) {
        if (!self.readerView) {
            
            self.readerView = [[ZBarReaderView alloc]init];
            self.readerView.frame=self.view.bounds;
            self.readerView.readerDelegate = self;
            self.readerView.tracksSymbols = NO;
            self.readerView.torchMode = 0;
            
            //二维码/条形码识别设置
            ZBarImageScanner *scanner = self.readerView.scanner;
            
            [scanner setSymbology: ZBAR_I25
                           config: ZBAR_CFG_ENABLE
                               to: 0];
            
            self.readerView.scanCrop = [self getScanCrop:SCANREGION
                                        readerViewBounds:self.readerView.bounds];
            
            [self.view addSubview:self.readerView];
            
        }
    }
 
    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:imgView];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.image=[UIImage imageNamed:@"qrbk"];
    
//    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"qdCodeToolbar" owner:self options:         nil];
//    toolbar=[nib objectAtIndex:0];
//    
//    toolbar.delegate=self;
//    toolbar.hasSystemNavBar=NO;
//    [toolbar showFromView:self.view Animated:NO completion:nil];
//
//    
}

-(void)startReading{
    [self.readerView start];
}


-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}


- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{
    NSString *result=nil;
    for (ZBarSymbol *symbol in symbols) {
        NSLog(@"rv %@", symbol.data);
        result=symbol.data;
        
        //编解码问题
        if ([result canBeConvertedToEncoding:NSShiftJISStringEncoding])
        {
            result = [NSString stringWithCString:[symbol.data cStringUsingEncoding: NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        }
        
        //如果转化成utf-8失败，再尝试转化为gbk
        if (result == nil)
            
        {
            result = [NSString stringWithCString:[symbol.data cStringUsingEncoding:NSShiftJISStringEncoding] encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
        }
        
        //如果转化为utf-8和gbk都失败，就显示原始扫描出来的字符串
        
        if (result == nil)
        {
            result = symbol.data;
        }
        
        break;
    }
    
    [self.readerView stop];
    
    if(result){
 
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        InputDeviceViewController *irvc = [board instantiateViewControllerWithIdentifier:@"inputlvc"];
        irvc.qrcode_device_id = result;
         [self.navigationController pushViewController:irvc animated:YES];
        
    }
    
}


#pragma mark -
#pragma mark UIImagePickerControllerDelegate

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.readerView start];
    }];
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        ZBarImage *zImage = [[ZBarImage alloc] initWithCGImage:image.CGImage];
        ZBarImageScanner *scanner = [[ZBarImageScanner alloc] init];
        [scanner setSymbology: ZBAR_I25
                       config: ZBAR_CFG_ENABLE
                           to: 0];
        [scanner scanImage:zImage];
        ZBarSymbolSet *set = [scanner results];
        
        NSString *result=nil;
        
        for (ZBarSymbol *symbol in set) {
            result =  symbol.data;
        }
        
        
        
        if (!result) {
 
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"图片不符合二维码规则" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
            
            
            [self.readerView start];
        }else{
 
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            InputDeviceViewController *irvc = [board instantiateViewControllerWithIdentifier:@"inputlvc"];
            irvc.qrcode_device_id = result;
            [self.navigationController pushViewController:irvc animated:YES];
        }
    }];
    
}


#pragma mark -
#pragma mark QdCodeToolbarDelegate
-(void)goback{
    
    [self.readerView stop];
//    [self dismissModalViewControllerAnimated:YES];
    
    [self.navigationController popViewControllerAnimated:YES];
}




-(void)pickPhoto{
    [self.readerView stop];
    
    UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
    mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    mediaUI.mediaTypes =  [UIImagePickerController         availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    mediaUI.allowsEditing = NO;
    mediaUI.delegate = self;
    [self presentViewController:mediaUI animated:YES completion:nil];
    
}
//-(void)light{
//    toolbar.lightBtn.selected = !toolbar.lightBtn.selected;
//    if (toolbar.lightBtn.selected) {
//        self.readerView.torchMode = 1;
//    }else{
//        self.readerView.torchMode = 0;
//        
//    }
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BOOL) shouldAutorotate {
    return NO;
}

// before 7.0
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == UIInterfaceOrientationPortrait;
}

// 7.0
- (NSUInteger)supportedInterfaceOrientations
{
    return  UIInterfaceOrientationMaskPortrait;
}

 @end
